from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosUser, collectionUserList, collectionUserRoleList
from app.globals.uuidTool import getuuId
from app.settings.base import super_administrator
from app.globals.publicMethod import globalGetNowTime
from app.db.dbDiningQuery import queryDiningName 
from app.db.dbStallQuery import queryStallName
from app.globals.publicMethod import globalStrMd5

def regeditUser(userName, userPwd, userRealName, 
                    userRoleId, userState, userDesc, RelationDiningNoList, RelationStallNo, login_userId):
    '''
    注册用户
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'roleId': userRoleId}
        collection = mg_client[dbSynPosUser][collectionUserRoleList]
        res = collection.find_one(cond)
        if res is None:
            return None

        #插入到用户数据库里
        collection = mg_client[dbSynPosUser][collectionUserList]
        res = collection.find_one({'userName': userName})
        userId = getuuId()
        #如果该用户存在
        if res is not None:
            return False

        now = globalGetNowTime()
        login_userName = getUserNameByuserId(login_userId)
        data = {
            'userId': userId,
            'userName': userName,
            'userPwd': userPwd,
            'userRealName': userRealName,
            'userRoleId': userRoleId,
            'userState': userState,
            'userDesc': userDesc,
            'RelationDiningNoList': RelationDiningNoList,
            'RelationStallNo': RelationStallNo,
            'creatorUserName': login_userName,
            'menderUserName': login_userName,
            'createTime': now,
            'updateTime': now
        }
        collection.insert_one(data)

        return userId
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def editUser(userId, userName, userRealName, 
                userRoleId, userState, userDesc, RelationDiningNoList, RelationStallNo, login_userId):
    '''
    编辑用户
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'userId': userId}
        collection = mg_client[dbSynPosUser][collectionUserList]

        now = globalGetNowTime()
        login_userName = getUserNameByuserId(login_userId)
        return collection.find_one_and_update(cond, 
                    {'$set': {
                            'userName': userName, 
                            'userRealName': userRealName, 
                            'userRoleId': userRoleId, 
                            'userState': userState,
                            'userDesc': userDesc,
                            'RelationDiningNoList': RelationDiningNoList,
                            'RelationStallNo': RelationStallNo,
                            'menderUserName': login_userName,
                            'updateTime': now
                        }
                    })
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def delUser(userId):
    '''
    删除用户
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'userId': userId}
        collection = mg_client[dbSynPosUser][collectionUserList]
        # 如果是超级用户, 不让删除
        res = collection.find_one({'userId': userId})
        if res is not None:
           resrole = mg_client[dbSynPosUser][collectionUserRoleList].find_one({'roleId': res['userRoleId']})
           if resrole is not None:
               if resrole['roleName'] == super_administrator:
                   return False

        return collection.find_one_and_delete(cond)
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def modifyPwd(userId, userPwdNew, userPwdOld):
    '''
    修改密码
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'userId': userId}
        collection = mg_client[dbSynPosUser][collectionUserList]
        res = collection.find_one(cond)
        if res is None:
            return None
        
        if res['userPwd'] != globalStrMd5(userPwdOld):
            return False

        return collection.find_one_and_update(cond, {'$set': {'userPwd': globalStrMd5(userPwdNew)}})   
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def getUserNameByuserId(userId):
    '''
    根据 userId 获取用户名
    '''
    try:
        mg_client = get_mongo_client()
        collectionUser = mg_client[dbSynPosUser][collectionUserList]
        res = collectionUser.find_one({'userId': userId})
        if res.get('userName') is not None:
            return res.get('userName')
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def resetPwd(userId, userPwd):
    '''
    重置其他用户密码
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'userId': userId}
        collection = mg_client[dbSynPosUser][collectionUserList]
        # 如果是超级用户, 不让重置
        res = collection.find_one({'userId': userId})
        if res is not None:
           resrole = mg_client[dbSynPosUser][collectionUserRoleList].find_one({'roleId': res['userRoleId']})
           if resrole is not None:
               if resrole['roleName'] == super_administrator:
                   return False

        return collection.find_one_and_update(cond, {'$set': {'userPwd': globalStrMd5(userPwd)}})
    except Exception as e:
        raise ErrMongoClient.data(str(e))